﻿using System;
using System.Collections.Generic;
using System.Text;

using Obsidian.Edm;
using Obsidian.Utils;
using Obsidian.Action;
using Oak.Core.Logic;
using Oak.Base;
using Oak.Model;

namespace Oak.Core.Serv
{
    public class ActPermServ : OakServ<OakSession>
    {

        private const string PERM_FIELDS = "itemId,appKeyId,actId,created";
        private const string ACTION_FIELDS = "actId,actName,actCatId,desc,modified,created";
        private const string LIST_ATTR_FIELDS = "itemsCount,pageNo,pageSize,pagesCount";

        public ActPermServ(OakSession session) : base(session) { }

        public void List(ActionRequest req, ActionResponse res)
        {
            CoActPermissionQry qry = req.GetModelByNameOrFirst<CoActPermissionQry>("qry");
            ActPermissionLG permLG = new ActPermissionLG(Session);
            ListAttrInfo listAttr;
            string msg;
            List<CoActPermissionInfo> list = permLG.GetPermissionList(qry, out listAttr, out msg);

            if (list == null)
            {
                res.Error(msg);
                return;
            }

            res.AddResult("perms", PERM_FIELDS, list)
                .SetRelation("action", "actId", "actions", "actId");
            res.AddResult("actions", ACTION_FIELDS, "actId", "action", list);

            res.AddResult("listAttr", LIST_ATTR_FIELDS, listAttr);
        }


        public void Add(ActionRequest req, ActionResponse res)
        {
            CoActPermissionInfo perm = req.GetModelByNameOrFirst<CoActPermissionInfo>("perm");
            ActPermissionLG permLG = new ActPermissionLG(Session);
            string msg;
            perm = permLG.AddPermission(perm, out msg);

            if (perm == null)
            {
                res.Error(msg);
                return;
            }

            res.AddResult("perms", PERM_FIELDS, perm)
                .SetRelation("action", "actId", "actions", "actId");
            res.AddResult("actions", ACTION_FIELDS, "actId", "action", perm);

        }

        public void Delete(ActionRequest req, ActionResponse res)
        {
            ActReqParam param;
            if (!req.TryGetParam("perm", out param))
            {
                res.Error("参数perm错误");
                return;
            }
            string strItemIds;
            if (!req.TryGetString("itemIds", out strItemIds))
            {
                res.Error("参数perm属性itemIds错误");
                return;
            }

            long[] itemIds = ArrayUtil.SplitInt64(strItemIds, ',');
            ActPermissionLG permLG = new ActPermissionLG(Session);
            string msg;
            bool succ = permLG.DeletePermissions(itemIds, out msg);
            if (!succ)
            {
                res.Error(msg);
                return;
            }

        }


    }
}
